/*
 * Copyright (c) 2010 Vadim Zhukov <persgray@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */


#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include "bitmap.h"


struct bitmap *
bm_init(size_t sz) {
	struct bitmap	*bm;
	size_t		 n;

	/* 31 = 2^5 - 1 */
	n = (sz & ~(size_t)31);
	if (sz & 31)
		n++;
	n >>= 5;
	bm = malloc(sizeof(struct bitmap) + n);
	if (bm == NULL)
		return NULL;
	bzero(bm, sizeof(struct bitmap) + n);
	bm->bm_len = sz;
	return bm;
}

void
bm_destroy(struct bitmap *bm) {
	free(bm);
}

int
bm_get(const struct bitmap *bm, size_t pos) {
	uint32_t	n;

	assert(pos < bm->bm_len);
	n = bm->bm_data[pos >> 5];
	n &= (1 << (pos & 31));
	n >>= (pos & 31);	/* Avoid problems on non-32-bit architectures */
	return (int)n;
}

void
bm_set(struct bitmap *bm, size_t pos, int v) {
	assert(pos < bm->bm_len);
	if (v)
		bm->bm_data[pos >> 5] |= (1 << (pos & 31));
	else
		bm->bm_data[pos >> 5] &= ~(1 << (pos & 31));
}
